package com.xsprite.managesys.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class DatabaseUtil {

	private static DatabaseUtil instance;

	private DatabaseUtil() {

	}

	public static DatabaseUtil getInstance() {
		if (instance == null) {
			instance = new DatabaseUtil();
		}
		return instance;
	}

	private Map<String, Connection> sqlConnectionMap = new HashMap<String, Connection>();

	public Connection getCachedConn(String url, String username, String pwd)
			throws ClassNotFoundException, SQLException {
		Connection conn = sqlConnectionMap.get(url);
		if (conn == null || conn.isClosed() || !conn.isValid(0)) {
			conn = createSqlConnection(url, username, pwd);
		}
		return conn;
	}

	// public Connection getConn(String url, String username, String pwd) throws
	// ClassNotFoundException, SQLException{
	// Connection conn = createSqlConnection(url, username, pwd);
	// return conn;
	// }

	private Connection createSqlConnection(String url, String username, String pwd)
			throws SQLException, ClassNotFoundException {
		String driver = "com.mysql.jdbc.Driver";// the MySQL driver
		Connection cn = null;
		Class.forName(driver);// add MySQL driver
		System.out.println("Database driver is successfully added");
		cn = DriverManager.getConnection(url, username, pwd);// create a
																// connection
																// object
		System.out.println("Database connection is successful");
		return cn;
	}
}
